import {
	Button,
	Card,
	Col,
	Empty,
	Pagination,
	Row,
	Space,
	Tag,
	Typography,
	Spin,
	Checkbox,
	message,
} from "antd";
import type { TaskItem } from "@/api/services/taskService";
import { useEffect, useState } from "react";
import dayjs from "dayjs";
import {
	MoneyCollectOutlined,
	ClockCircleOutlined,
	PaperClipOutlined,
	EyeOutlined,
	DownloadOutlined,
} from "@ant-design/icons";
import DocPreview from "@/components/DocPreview";

interface TaskTableProps {
	loading: boolean;
	taskList: TaskItem[];
	currentPage: number;
	pageSize: number;
	total: number;
	onPageChange: (page: number, size: number) => void;
	onViewDetail: (task: TaskItem) => void;
}

const TaskTable = ({
	loading,
	taskList,
	currentPage,
	pageSize,
	total,
	onPageChange,
	onViewDetail,
}: TaskTableProps) => {
	const [animate, setAnimate] = useState(false);
	const [previewVisible, setPreviewVisible] = useState(false);
	const [previewUrl, setPreviewUrl] = useState("");
	const [selectedTasks, setSelectedTasks] = useState<TaskItem[]>([]);

	useEffect(() => {
		setAnimate(true);
		const timer = setTimeout(() => setAnimate(false), 400);
		return () => clearTimeout(timer);
	}, [taskList]);

	const handlePreview = (e: React.MouseEvent, url: string) => {
		e.stopPropagation();
		setPreviewUrl(url);
		setPreviewVisible(true);
	};

	const handleClosePreview = () => {
		setPreviewVisible(false);
		setPreviewUrl("");
	};

	const handleDownload = (e: React.MouseEvent, url: string) => {
		e.stopPropagation();
		const link = document.createElement("a");
		link.href = url;
		link.download = "";
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
	};

	const handleBatchDownload = () => {
		if (selectedTasks.length === 0) {
			message.warning("请先选择要下载的任务");
			return;
		}

		// 检查选中的任务是否都有附件
		const tasksWithoutAttachment = selectedTasks.filter(
			(task) => !task.attachment,
		);
		if (tasksWithoutAttachment.length > 0) {
			message.error(`有${tasksWithoutAttachment.length}个任务没有附件`);
			return;
		}

		message.loading("正在准备下载...", 0);

		const downloads = selectedTasks.map((task, index) => {
			return new Promise((resolve, reject) => {
				setTimeout(() => {
					try {
						if (!task.attachment) {
							throw new Error("文件不存在");
						}
						const link = document.createElement("a");
						link.href = task.attachment;
						link.download = task.name || ""; // 使用任务名称作为文件名
						document.body.appendChild(link);
						link.click();
						document.body.removeChild(link);
						message.success(`${task.name || "文件"} 开始下载`);
						resolve(true);
					} catch (error) {
						message.error(`${task.name || "文件"} 下载失败`);
						reject(error);
					}
				}, index * 500); // 减少间隔到500ms
			});
		});

		Promise.all(downloads)
			.then(() => {
				message.destroy(); // 清除loading消息
				message.success(`共${selectedTasks.length}个文件下载完成`);
			})
			.catch((error) => {
				message.destroy(); // 清除loading消息
				message.error("部分文件下载失败，请重试");
				console.error("Download error:", error);
			});
	};

	const handleSelectTask = (e: React.MouseEvent, task: TaskItem) => {
		e.stopPropagation();
		const isSelected = selectedTasks.some((t) => t.id === task.id);
		if (isSelected) {
			setSelectedTasks(selectedTasks.filter((t) => t.id !== task.id));
		} else {
			setSelectedTasks([...selectedTasks, task]);
		}
	};

	const renderTaskCard = (record: TaskItem, index: number) => (
		<Col xs={24} sm={24} md={24} lg={24} key={record.id}>
			<div className={`task-card-wrapper ${animate ? "animate-in" : ""}`}>
				<Card
					hoverable
					className="task-card"
					bodyStyle={{ padding: "10px", backgroundColor: "#e6f7ff" }}
					onClick={() => onViewDetail(record)}
				>
					<div className="task-card-content">
						<div
							className="task-header"
							style={{
								display: "flex",
								alignItems: "center",
								marginBottom: "12px",
								gap: "8px",
							}}
						>
							<Checkbox
								checked={selectedTasks.some((t) => t.id === record.id)}
								onClick={(e) => handleSelectTask(e, record)}
								style={{ marginRight: "8px" }}
								disabled={!record.attachment}
							/>
							<Typography.Text
								type="secondary"
								style={{ fontSize: "14px", minWidth: "60px" }}
							>
								#{record.id}
							</Typography.Text>
							<Tag color="cyan" style={{ margin: 0 }}>
								{record.category?.name}
							</Tag>
							<Tag
								color={record.status === 1 ? "success" : "default"}
								style={{ margin: 0, marginLeft: "auto" }}
							>
								{record.status_text}
							</Tag>
						</div>
						<div className="task-main">
							<div
								style={{ marginBottom: "0px", display: "flex", gap: "10px" }}
							>
								{record.image && (
									<div
										className="task-image"
										style={{
											width: "50px",
											height: "50px",
											flexShrink: 0,
											borderRadius: "9999px",
											overflow: "hidden",
										}}
									>
										<img
											src={record.image}
											alt={record.title}
											style={{
												width: "100%",
												height: "100%",
												borderRadius: "9999px",
												objectFit: "cover",
											}}
											onError={(e) => {
												const target = e.target as HTMLImageElement;
												target.src =
													"";
											}}
										/>
									</div>
								)}
								<div style={{ flex: 1 }}>
									<Typography.Text
										level={4}
										ellipsis={{ rows: 2 }}
										style={{ margin: 0, fontSize: "16px" }}
									>
										{record.title}
									</Typography.Text>
								</div>
							</div>
							<div
								style={{
									display: "flex",
									justifyContent: "space-between",
									alignItems: "flex-end",
									marginTop: "auto",
								}}
							>
								<div
									className="info-item"
									style={{ display: "flex", alignItems: "center", gap: "4px" }}
								>
									<MoneyCollectOutlined
										style={{ fontSize: "16px", color: "#f5222d" }}
									/>
									<Typography.Text
										type="secondary"
										style={{ fontSize: "18px", color: "#f5222d" }}
									>
										¥{record.price}
									</Typography.Text>
								</div>
								<div
									className="task-actions"
									style={{ display: "flex", gap: "8px" }}
								>
									{record.attachment && (
										<>
											<Button
												type="primary"
												style={{
													backgroundColor: "#1890ff",
													borderColor: "#1890ff",
													borderRadius: "20px",
												}}
												onClick={(e) => handlePreview(e, record.attachment)}
											>
												预览
											</Button>
											<Button
												type="primary"
												style={{
													backgroundColor: "#1890ff",
													borderColor: "#1890ff",
													borderRadius: "20px",
												}}
												onClick={(e) => handleDownload(e, record.attachment)}
											>
												下载
											</Button>
										</>
									)}
									<Button
										type="primary"
										style={{
											backgroundColor: "#52c41a",
											borderColor: "#52c41a",
											borderRadius: "20px",
										}}
										onClick={() => onViewDetail(record)}
									>
										交单
									</Button>
								</div>
							</div>
						</div>
					</div>
				</Card>
			</div>
		</Col>
	);

	return (
		<div className="task-grid-container">
			<Spin spinning={loading} size="large" tip="加载中...">
				{selectedTasks.length > 0 && (
					<div style={{ marginBottom: "16px", textAlign: "right" }}>
						<Button
							onClick={() => {
								const tasksWithAttachment = taskList.filter(
									(task) => task.attachment,
								);
								if (selectedTasks.length === tasksWithAttachment.length) {
									setSelectedTasks([]);
								} else {
									setSelectedTasks(tasksWithAttachment);
								}
							}}
							style={{
								marginRight: "8px",
								borderRadius: "20px",
							}}
						>
							{selectedTasks.length ===
							taskList.filter((task) => task.attachment).length
								? "取消全选"
								: "全选"}
						</Button>
						<Button
							type="primary"
							onClick={handleBatchDownload}
							style={{
								backgroundColor: "#1890ff",
								borderColor: "#1890ff",
								borderRadius: "20px",
							}}
						>
							批量下载 ({selectedTasks.length})
						</Button>
					</div>
				)}
				{taskList.length > 0 ? (
					<>
						<Row gutter={[0, 8]}>
							{taskList.map((record, index) => renderTaskCard(record, index))}
						</Row>
						<div className="pagination-container">
							<Pagination
								current={currentPage}
								pageSize={pageSize}
								total={total}
								onChange={onPageChange}
								showSizeChanger={false}
								showQuickJumper
							/>
						</div>
					</>
				) : (
					<Empty
						description="暂无任务"
						image={Empty.PRESENTED_IMAGE_SIMPLE}
						className="empty-container"
					/>
				)}
			</Spin>
			<DocPreview
				url={previewUrl}
				visible={previewVisible}
				onClose={handleClosePreview}
			/>
		</div>
	);
};

export default TaskTable;
